#include "mytcpserver.h"

MyTcpServer::MyTcpServer()
{


}

MyTcpServer &MyTcpServer::getInstance()
{
    static MyTcpServer instance;
    return instance;
}

void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
    MyTcpSocket *pTcpSocket = new MyTcpSocket;
    pTcpSocket->setSocketDescriptor(socketDescriptor);
    m_tcpSocketList.append(pTcpSocket);
    connect(pTcpSocket, SIGNAL(offline(MyTcpSocket *)), this, SLOT(deleteSocket(MyTcpSocket *)));
}
bool MyTcpServer::forwardMsg(const QString caDesName, PDU *pdu)
{
    if(caDesName == NULL || pdu == NULL)
    {
        return false;
    }
    // 查找目标用户名的Socket
    for(int i = 0; i < m_tcpSocketList.size(); ++ i)
    {
        if(caDesName == m_tcpSocketList.at(i) -> getStrName())
        {
            m_tcpSocketList.at(i)->write((char*)pdu, pdu -> uiPDULen);
            return true;
        }
    }

    return false;
}
void MyTcpServer::deleteSocket(MyTcpSocket *mySocket)
{
    QList<MyTcpSocket*>::iterator iter = m_tcpSocketList.begin();
    for(; iter != m_tcpSocketList.end(); iter ++)
    {
        if(mySocket == *iter)
        {
            (*iter) -> deleteLater();
            *iter = NULL;
            m_tcpSocketList.erase(iter);
            break;
        }
    }
}

